﻿using WorldMapBase;
using WorldMapBase.Layer;
using System.Collections.Generic;
using Unity.Mathematics;
using UnityEngine;

public class TestTinyPool
{
    private Stack<TestCube> stack = new Stack<TestCube>();

    public TestCube Pop()
    {
        if (stack.Count > 0)
        {
            return stack.Pop();
        }
        else
        {
            return new TestCube();
        }
    }

    public void Push(TestCube testCube)
    {
        stack.Push(testCube);
    }
}

public class TestCube
{
    public int lodLevel;
    public int tileIndex;
    public int2 worldPos;
}

public class TestCubeRenderer : MonoBehaviour
{
    private Dictionary<int, Dictionary<int, TestCube>> renderInfoDic = new Dictionary<int, Dictionary<int, TestCube>>();
    private TestTinyPool testTinyPool = new TestTinyPool();

    public void AddCube(int lodLevel, int tileIndex, int2 worldPos)
    {
        var cube = testTinyPool.Pop();
        cube.lodLevel = lodLevel;
        cube.tileIndex = tileIndex;
        cube.worldPos = worldPos;

        Dictionary<int, TestCube> dic;
        if (!renderInfoDic.TryGetValue(lodLevel, out dic))
        {
            dic = new Dictionary<int, TestCube>();
            renderInfoDic.Add(lodLevel, dic);
        }

        dic.Add(tileIndex, cube);
    }

    public void RemoveCube(int lodLevel, int tileIndex)
    {
        var dic = renderInfoDic[lodLevel];
        var cube = dic[tileIndex];
        testTinyPool.Push(cube);
        dic.Remove(tileIndex);
    }

    private void OnDrawGizmos()
    {
        foreach (var cubeDic in renderInfoDic.Values)
        {
            foreach (var cube in cubeDic.Values)
            {
                Gizmos.DrawCube(new Vector3(cube.worldPos.x, 0, cube.worldPos.y), new Vector3(90, 90, 90));
            }
        }
    }
}

public class SampleTileLODListener : ITileLayerListener, LODTileLayer.ILODScaleListener
{
    private int m_LayerID;
    private TestCubeRenderer m_TestCubeRenderer;

    public SampleTileLODListener(int layerID)
    {
        m_LayerID = layerID;

        GameObject obj = new GameObject("TestCubeGizmos");
        m_TestCubeRenderer = obj.AddComponent<TestCubeRenderer>();
    }

    public void OnAddTile(int lodLevel, int tileIndex, int2 worldPos)
    {
        Debug.LogError(string.Format("添加层级{0}，LOD等级{1}，地块序号为{2}，世界坐标为({3}, {4})的地块", m_LayerID, lodLevel, tileIndex, worldPos.x, worldPos.y));
        m_TestCubeRenderer.AddCube(lodLevel, tileIndex, worldPos);
    }

    public void OnLODScaleUpdate(int lodLevel, float percent)
    {
        Debug.LogError(string.Format("调整层级{0}，LOD等级{1}的百分比为{2}", m_LayerID, lodLevel, percent));
    }

    public void OnRemoveTile(int lodLevel, int tileIndex)
    {
        Debug.LogError(string.Format("移除层级{0}，LOD等级{1}，地块序号为{2}的地块", m_LayerID, lodLevel, tileIndex));
        m_TestCubeRenderer.RemoveCube(lodLevel, tileIndex);
    }

    public void OnRemoveTiles(int id, int[] tilesIndexs)
    {
        
    }
}
